part of YFree;

class YFreeWebPlugin {
  static void registerWith(dynamic registrar) {}
}

class _YFreeWebPlugin extends _YFreeCommonPlugin {
  _YFreeWebPlugin() {
    final postMessageKey = "${runtimeType.toString()}_${Ulid().toCanonical()}";
    invokeMethod("yRegisterPlugin", args: [
      YConfig.DEBUG ? "1" : "0",
      postMessageKey,
    ]);
    html.window.onMessage.listen((event) {
      final data = event.data.toString();
      if (data.startsWith(postMessageKey)) {
        final params = json.decode(data.split("${postMessageKey}_")[1]);
        yPages.forEach((yPage) {
          if (yPage.runtimeType.toString().replaceAll("\$", "") == params["page"]) yPage.yOnYFreeCall(params["method"], params["params"]);
        });
      }
    });
  }

  dynamic invokeMethod(String method, {List? args}) {
    return args != null ? js.context.callMethod(method, args) : js.context.callMethod(method);
  }

  @override
  void finishApplication() {}
}
